/*
 *  Copyright (c) 2022 李伟国
 *  online-judge is licensed under Mulan PSL v2.
 *  You can use this software according to the terms and conditions of the Mulan PSL v2.
 *  You may obtain a copy of Mulan PSL v2 at:
 *          http://license.coscl.org.cn/MulanPSL2
 *  THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 *  See the Mulan PSL v2 for more details.
 */

package edu.platform.controller;

import com.alibaba.fastjson.JSON;
import edu.platform.config.ConfigSourceProperties;
import edu.platform.dto.CodeMsg;
import edu.platform.dto.RunResult;
import edu.platform.entity.Runner;
import edu.platform.service.IJudgeService;
import edu.platform.utils.CodeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping(value = "code")
public class RunController {
    @Autowired
    private IJudgeService judgeService;

    @Autowired
    private ConfigSourceProperties configSourceProperties;

    @RequestMapping(value = "run", method = RequestMethod.POST)
    public RunResult runCode(@RequestBody CodeMsg codeMsg) {
        if(codeMsg.getCode().equals("")){
            return null;
        }
        String filePrefix = CodeUtils.filePrefix;
        String fileSuffix = CodeUtils.fileSuffix.get(codeMsg.getLang());
        String filePath = judgeService.createFile(codeMsg.getCode(), filePrefix, fileSuffix);
        Runner runner = new Runner();
        runner.setFileSuffix(fileSuffix)
                .setFilePrefix(filePrefix)
                .setFilePath(filePath)
                .setLanguage(codeMsg.getLang())
                .setCodeResultDir(filePath)
                .setTestDir(configSourceProperties.getTestData())
                .setLanguageDir(configSourceProperties.getLanguageConfig())
                .setJudgePath(configSourceProperties.getOnlineJudge());
        List<Object> running = judgeService.Running(runner.toString());
        RunResult runResult = new RunResult();
        int size = running.size();
        runResult.setRunResult(JSON.parse(String.valueOf(running.get(size-1))));
        runResult.setCompileResult(
                running.stream()
                        .limit(size-1)
                        .collect(Collectors.toList()));

        return runResult;
    }
}